import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-04-06
 * Time: 23:02
 */


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    // 前缀和

    public HashMap<Long, Integer> prefix;

    public int count=0;
    public int pathSum(TreeNode root, int targetSum) {
        this.prefix=new HashMap<>();
        prefix.put(0L, 1);
        dfs(root, targetSum, 0);
        return count;
    }

    public void dfs(TreeNode root, int targetSum, long sum){
        if(root==null){
            return ;
        }
        sum += root.val;
        count += prefix.getOrDefault(sum - targetSum, 0);
        prefix.put(sum, prefix.getOrDefault(sum, 0) + 1);
        dfs(root.left, targetSum, sum);
        dfs(root.right, targetSum, sum);
        prefix.put(sum, prefix.get(sum) - 1);
    }
}
